<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="hadd">新增员工</el-button>
        </template>
      </page-tools>

      <el-dialog
        title="新增员工"
        :visible.sync="dialogVisible"
        width="40%"
      >
        <addorEdit
          v-if="dialogVisible"
          @success="hSuccess"
        />
      </el-dialog>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop:'timeOfEntry',order:'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />

          <el-table-column label="员工头像" width="100">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" srcset="" style="width:100%" @click="showQrCode(row.staffPhoto)">
              <template />
            </template></el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ FormData(row.formOfEmployment) }}
              <template />
            </template></el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?userId=${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="size"
            :current-page="page"
            layout="prev,pager,next"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="二维码" :visible.sync="showCodeDialog" width="300px">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <el-dialog :visible.sync="showDialogRole">
        <AssignRole
          v-if="showDialogRole"
          :cur-id="curEmployeId"
          @close="showDialogRole=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
// import PageTools from '@/components/PageTools'
import { deleEmployees, getupEmployees } from '@/api/employees'
import addorEdit from './empDialog'
import employeesEnum from '@/constant/employees'
import { transZhKeyToExcel } from '@/utils'
import QrCode from 'qrcode'
import AssignRole from './assignRole.vue'
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
export default {
  name: 'Employees',
  components: {
    addorEdit,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 10,
      total: 0,
      dialogVisible: false,
      showCodeDialog: false,
      showDialogRole: false,
      curEmployeId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  mounted() {

  },

  methods: {
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const { tHeader, data } = transZhKeyToExcel(this.list)
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(fil1terVal, list)
        // const data = [[1, '三体', '刘慈欣', 10000, '2022-11-05'], [2, '三体2', '刘慈欣2', 20000, '2022-11-08']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    FormData(id) {
    // return employeesEnum.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    // 渲染表格
    async loadEmployeeList() {
      try {
        const res = await getupEmployees({ page: this.page, size: this.size })
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // 翻页功能
    hCurrentChange(val) {
      this.page = val
      this.loadEmployeeList()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    hadd() {
      this.dialogVisible = true
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployeeList()
      this.dialogVisible = false
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleEmployees(id)
        if (res.code === 10000) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.loadEmployeeList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hAssignRole(id) {
      this.curEmployeId = id
      this.showDialogRole = true
    }
  }
}
</script>

<style lang="sass" scoped>

</style>
